package com.alili_tv.system.common;

import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.time.Duration;
import java.time.LocalDateTime;

@Getter
@Setter
@AllArgsConstructor
public class SessionCache {

    private Long userId;

    private LocalDateTime createTime;

    public static SessionCache create(Long userId) {
        return new SessionCache(userId, LocalDateTime.now());
    }

    /**
     * 建立session缓存
     * @param session
     * @param userId
     */
    public static void cache(HttpSession session, Long userId) {
        session.setMaxInactiveInterval(259200); // 过期时间为3天
        session.setAttribute("AUTHORITY", SessionCache.create(userId));
    }

    /**
     * 刷新session缓存
     * @param cacheInfo
     * @param session
     */
    public static void refresh(SessionCache cacheInfo, HttpSession session) {
        // 计算剩余时间（d）
        Duration duration = Duration.between(cacheInfo.getCreateTime(), LocalDateTime.now());
        long expire = duration.toDays();

        // 若剩余时间不如2天则刷新缓存
        if (expire < 2) {
            cache(session, cacheInfo.getUserId());
        }
    }

    /**
     * 删除session缓存
     * @param session
     */
    public static void delete(HttpSession session) {
        session.removeAttribute("AUTHORITY");
    }
}
